package com.hotel_management_backstage.lin.service.staffManagement;

import com.hotel_management_backstage.lin.dao.staffManagement.SysStaffMapper;
import com.hotel_management_backstage.lin.entity.SysUser;
import com.hotel_management_backstage.lin.entity.staffManagement.SysStaff;
import com.hotel_management_backstage.lin.entity.staffManagement.SysUserStaff;
import com.hotel_management_backstage.lin.service.SysUserService;
import com.hotel_management_backstage.lin.utils.security.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class SysStaffService {

    @Autowired
    private SysStaffMapper sysStaffMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserStaffService sysUserStaffService;

    void insertSysStaff(SysStaff sysStaff){
        sysStaffMapper.insertSysStaff(sysStaff);
    }

    void updateSysStaff(SysStaff sysStaff){
        sysStaffMapper.updateSysStaffById(sysStaff);
    }

    SysStaff selectByStaffNumber(int staffNumber){
        return sysStaffMapper.selectByStaffNumber(staffNumber);
    }

    List<SysStaff> selectAllStaff(){
        return sysStaffMapper.selectAllStaff();
    }

    public SysStaff getSysStaffByCurrentUsername(HttpServletRequest request){
        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            return null;
        }
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        String username = JwtTokenUtils.getUsername(token);
        SysUser sysUser = sysUserService.selectByName(username);
        SysUserStaff sysUserStaff = sysUserStaffService.selectByUserId(sysUser.getId());
        return sysStaffMapper.selectStaffById(sysUserStaff.getStaffId());
    }

    public void deleteSysStaffById(int id){
        sysStaffMapper.deleteSysStaffById(id);
    }
}
